package com.yonyou.sto.modules.ims.controller;


import com.yonyou.sto.common.api.CommonResult;
import com.yonyou.sto.common.domain.DownloadFile;
import com.yonyou.sto.modules.ims.model.ImsInvoice;
import com.yonyou.sto.modules.ims.model.ImsInvoiceItem;
import com.yonyou.sto.modules.ims.service.ImsInvoiceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpStatus;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 单据管理前端控制器
 * </p>
 *
 * @author aegon
 * @since 2020-09-15
 */
@RestController
@RequestMapping("/server/ims/imsInvoice")
@Api(tags = "ImsInvoiceController", description = "单据管理")
public class ImsInvoiceController {

    @Resource
    private ImsInvoiceService imsInvoiceService;


    @ApiOperation("已开票条件分页查询开票数据")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<Map<String, Object>> list(Principal principal,
                                                  @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize,
                                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                  @RequestParam(value = "billSerial", required = false) String billSerial,
                                                  @RequestParam(value = "billSn", required = false) String billSn,
                                                  @RequestParam(value = "billType", required = false) String billType,
                                                  @RequestParam(value = "billNo", required = false) String billNo,
                                                  @RequestParam(value = "billCode", required = false) String billCode,
                                                  @RequestParam(value = "sellerName", required = false) String sellerName,
                                                  @RequestParam(value = "buyerName", required = false) String buyerName,
                                                  @RequestParam(value = "status", required = false) Integer status,
                                                  @RequestParam(value = "startTime", required = false) String startTime,
                                                  @RequestParam(value = "endTime", required = false) String endTime,
                                                  @RequestParam(value = "djlx", required = false) String djlx,
                                                  @RequestParam(value = "applyname", required = false) String applyname,
                                                  @RequestParam(value = "ncName", required = false) String ncName)

    {
        if (principal == null) return CommonResult.unauthorized(null);

        List<Integer> statusList = new ArrayList<>();
        if(status!=null){
            statusList.add(status);
        }else {
            statusList.add(2);
            statusList.add(5);
        }
        return imsInvoiceService.list(principal.getName(), pageSize, pageNum,billSerial, billSn,billNo,billCode ,sellerName, buyerName, statusList, startTime, endTime,djlx,billType,applyname,ncName);

//        return imsInvoiceService.list(principal.getName(), pageSize, pageNum,billSerial, billSn,billNo,billCode ,sellerName, buyerName, status, startTime, endTime,djlx);
    }
    @ApiOperation("开票申请条件分页查询开票数据")
    @RequestMapping(value = "/listApply", method = RequestMethod.GET)
    public CommonResult<Map<String, Object>> listApply(Principal principal,
                                                  @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize,
                                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                  @RequestParam(value = "billSn", required = false) String billSn,
                                                  @RequestParam(value = "sellerName", required = false) String sellerName,
                                                  @RequestParam(value = "buyerName", required = false) String buyerName,
                                                  @RequestParam(value = "djlx", required = false) String djlx,
                                                  @RequestParam(value = "status", required = false) Integer status,
                                                  @RequestParam(value = "startTime", required = false) String startTime,
                                                  @RequestParam(value = "endTime", required = false) String endTime,
                                                       @RequestParam(value = "applyname", required = false) String applyname)

    {
        if (principal == null) return CommonResult.unauthorized(null);
        List<Integer> statusList = new ArrayList<>();
        if(status==null||status==0){
            statusList.add(3);
            statusList.add(4);
            statusList.add(9);
        }else {
            statusList.add(status);
        }
        return imsInvoiceService.list(principal.getName(), pageSize, pageNum,null, billSn,null,null, sellerName, buyerName, statusList, startTime, endTime,djlx,null,applyname,null);
//        return imsInvoiceService.listApply(principal.getName(), pageSize, pageNum, billSn, sellerName, buyerName, djlx, status, startTime, endTime);
    }

    @ApiOperation("待开票条件分页查询开票数据")
    @RequestMapping(value = "/listNotice", method = RequestMethod.GET)
    public CommonResult<Map<String, Object>> listNotice(Principal principal,
                                                       @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize,
                                                       @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                       @RequestParam(value = "billSn", required = false) String billSn,
                                                       @RequestParam(value = "sellerName", required = false) String sellerName,
                                                       @RequestParam(value = "buyerName", required = false) String buyerName,
                                                       @RequestParam(value = "applyname", required = false) String applyname,
                                                       @RequestParam(value = "djlx", required = false) String djlx,
                                                       @RequestParam(value = "startTime", required = false) String startTime,
                                                       @RequestParam(value = "endTime", required = false) String endTime,
                                                        @RequestParam(value = "ncName", required = false) String ncName)

    {
        if (principal == null) return CommonResult.unauthorized(null);
        List<Integer> statusList = new ArrayList<>();
        statusList.add(1);
        return imsInvoiceService.list(principal.getName(), pageSize, pageNum, null,billSn,null,null, sellerName, buyerName, statusList, startTime, endTime,djlx,null,applyname,ncName);
//        return imsInvoiceService.listNotice(principal.getName(), pageSize, pageNum, billSn, sellerName, buyerName, djlx, startTime, endTime);
    }

    @ApiOperation("已红冲件分页查询开票数据")
    @RequestMapping(value = "/listHongchong", method = RequestMethod.GET)
    public CommonResult<Map<String, Object>> listHongchong(Principal principal,
                                                        @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize,
                                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                        @RequestParam(value = "billSerial", required = false) String billSerial,
                                                        @RequestParam(value = "billSn", required = false) String billSn,
                                                        @RequestParam(value = "sellerName", required = false) String sellerName,
                                                        @RequestParam(value = "buyerName", required = false) String buyerName,
                                                        @RequestParam(value = "djlx", required = false) String djlx,
                                                        @RequestParam(value = "startTime", required = false) String startTime,
                                                        @RequestParam(value = "endTime", required = false) String endTime,
                                                           @RequestParam(value = "ncName", required = false) String ncName,
                                                           @RequestParam(value = "applyname", required = false) String applyname)

    {
        if (principal == null) return CommonResult.unauthorized(null);
        List<Integer> statusList = new ArrayList<>();
        statusList.add(1);
        return imsInvoiceService.list(principal.getName(), pageSize, pageNum, billSerial,billSn,null,null, sellerName, buyerName, statusList, startTime, endTime,djlx,null,applyname,ncName);
//        return imsInvoiceService.listNotice(principal.getName(), pageSize, pageNum, billSn, sellerName, buyerName, djlx, startTime, endTime);
    }
    @ApiOperation("开票申请条件分页查询开票数据")
    @RequestMapping(value = "/merge", method = RequestMethod.POST)
    public CommonResult<Map<String, Object>> merge(Principal principal,@RequestParam List<String> ids)
    {
        if (principal == null) return CommonResult.unauthorized(null);

        return imsInvoiceService.merge(ids);
    }

    @ApiOperation("开票申请条件分页查询开票数据")
    @RequestMapping(value = "/mergeList", method = RequestMethod.POST)
    public CommonResult<Map<String, Object>> mergeList(Principal principal,@RequestParam List<String> ids) {
        if (principal == null) return CommonResult.unauthorized(null);

        return imsInvoiceService.mergeList(ids);
    }

    @ApiOperation("开票申请条件分页查询开票数据")
    @RequestMapping(value = "/applyList", method = RequestMethod.POST)
    public CommonResult<Map<String, Object>> ApplyList(Principal principal,@RequestParam List<String> ids) {
        if (principal == null) return CommonResult.unauthorized(null);
        return imsInvoiceService.applyList(principal.getName(),ids);
    }


    @ApiOperation("修改单据信息")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public CommonResult update(@RequestBody ImsInvoice invoice) {
        invoice.setId(invoice.getId());
        imsInvoiceService.updateById(invoice);
        return CommonResult.success("修改成功");
    }

    @ApiOperation("修改单据明细信息")
    @RequestMapping(value = "/updateRedapplycode/{id}", method = RequestMethod.POST)
    public CommonResult updateRedapplycode(@PathVariable String id,@RequestBody() String name) {
        ImsInvoice byId = imsInvoiceService.getById(id);
        if (byId==null){
            return CommonResult.success("未查询到指定单据信息");
        }
        byId.setRedapplycode(name);
        boolean result = imsInvoiceService.updateById(byId);
        if (result){
            return CommonResult.success("修改红字申请单号成功");
        }else {
            return CommonResult.failed("修改红字申请单号失败");
        }
    }

    @ApiOperation("修改单据备注")
    @RequestMapping(value = "/updateNote/{id}", method = RequestMethod.POST)
    public CommonResult updateNote(@PathVariable String id,@RequestBody() String name) {
        ImsInvoice byId = imsInvoiceService.getById(id);
        if (byId==null){
            return CommonResult.success("未查询到指定单据信息");
        }
        byId.setNote(name);
        boolean result = imsInvoiceService.updateById(byId);
        if (result){
            return CommonResult.success("修改备注成功");
        }else {
            return CommonResult.failed("修改备注失败");
        }
    }

    @ApiOperation("批量删除单据")
    @RequestMapping(value = "/deleteInvoice", method = RequestMethod.POST)
    public CommonResult deleteInvoice(@RequestBody List<String> ids) {
        return imsInvoiceService.deleteInvoice(ids);
    }

    @ApiOperation("批量退回单据到悦闻")
    @RequestMapping(value = "/returnInvoice", method = RequestMethod.POST)
    public CommonResult returnInvoice(@RequestBody List<String> ids) {
        return imsInvoiceService.returnInvoice(ids);
    }

    @ApiOperation("查询单据明细和退回记录")
    @GetMapping(value = "/invoiceInfo")
    public CommonResult invoiceInfo(@RequestParam String id) {
        return imsInvoiceService.invoiceInfo(id);
    }

    @ApiOperation("批量作废发票")
    @PostMapping(value = "/cancel")
    public CommonResult<String> cancel(@RequestBody List<String> ids,Principal principal) {
        return imsInvoiceService.cancel(ids,principal);
    }

    @ApiOperation(value = "导出当前页面的发票数据")
    @GetMapping(value = "/downloadFile")
    public void downloadFile(Principal principal,
                            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
                             @RequestParam(value = "billSerial", required = false) String billSerial,
                             @RequestParam(value = "billSn", required = false) String billSn,
                             @RequestParam(value = "billNo", required = false) String billNo,
                             @RequestParam(value = "billCode", required = false) String billCode,
                             @RequestParam(value = "sellerName", required = false) String sellerName,
                             @RequestParam(value = "buyerName", required = false) String buyerName,
                             @RequestParam(value = "status", required = false) Integer status,
                             @RequestParam(value = "startTime", required = false) String startTime,
                             @RequestParam(value = "endTime", required = false) String endTime,
                             @RequestParam(value = "djlx", required = false) String djlx,
                            HttpServletRequest request, HttpServletResponse response){
        String filename = "已开票信息.xlsx";
        XSSFWorkbook workbook = imsInvoiceService.downLoadPageNumInvoice(principal.getName(), pageSize, pageNum, billSerial, billSn, billNo, billCode, sellerName, buyerName, status, startTime, endTime, djlx);
        try {
            OutputStream myout = null;
            // 检查时候获取到数据
            if (workbook == null) {
                response.sendError(HttpStatus.SC_NOT_FOUND);
            }
            try {
                if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                    filename = new String(filename.getBytes("GBK"), "iso-8859-1");
                } else {
                    filename = URLEncoder.encode(filename, "utf-8");
                }
                response.setContentType("multipart/form-data");
                /*response.setContentType("multipart/form-data;charset=utf-8");*/
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                // 写明要下载的文件的大小
                //response.setContentLength(fileData.length);
                // 从response对象中得到输出流,准备下载
                myout = response.getOutputStream();
                workbook.write(myout);
                myout.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (myout != null) {
                    try {
                        myout.close();
                    } catch (Exception e) {
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

